import os, tarfile, pdb, re, time
from errors import *

class sosreport_class:

   def __init__(self, path, parent_host):

      self.parent_host = parent_host

      self.sysreport = True

      if type(path) == tarfile.TarFile:

         self.tar = path
         self.path_root = self.tar.first.name

      elif os.path.isfile(path) and tarfile.is_tarfile(path):

         self.tar = tarfile.open(path, "r")
         self.path_root = self.tar.next().name.rstrip("/")

      elif os.path.isdir(path):

         self.tar = None
         self.path_root = path

      self.path_root = self.path_root.rstrip("/")

      if self.open("sos_commands"):
         self.sysreport = False

      if not self.sysreport and not self.open("sos_commands"):
         raise

      sar = sar_class()
      sar.add_file("/misc/ibook/lvm_144277/ux061-184518/var/log/sa/sar13")

   def extract_all(self, path):

      if not self.tar:
         return

      if self.tar.extractall(path):
         self.tar = None
         self.path_root = path + "/" + self.path_root
         return True

      return False

   def get_member(self, fname, follow_links = True):

      fname = fname.lstrip("/")

      while True:

         try:
            toret = self.tar.getmember( "%s/%s" % (self.path_root, fname) )
         except:
            print "cannot find %s/%s" % (self.path_root, fname)
            raise

         if follow_links and not toret.isfile():
            fname = toret.linkname
            toret = None

         if toret:
            return toret

   def has_file(self, fname):
      return self.open(fname) != None

   def extract(self, fname, path):

      self.tar.extract( self.get_member(fname), path = path)

   def get_real_file(self, fname):

      if not self.tar:
         return "%s/%s" % (self.path_root, fname)

      else:
         tar.extract( self.get_member(fname), path = self.parent_host.parent_cluster.CONFIG["tmpdir"] )

   def open(self, fname):

      if not self.tar:

         try:
            fp = open("%s/%s" % (self.path_root, fname), "r")
         except IOError:
            fp = None

      else:

         try:
            fp = self.tar.extractfile( self.get_member( fname ) )
         except KeyError:
            fp = None

      if self.sysreport and fp:
         fp.readline()

      return fp

   def open_and_read(self, fname):

      fp = self.open(fname)

      if not fp:
         return ""

      toret = fp.read()
      fp.close()
      return toret

   def open_and_readlines(self, fname):

      fp = self.open(fname)

      if not fp:
         raise StopIteration

      while True:

         toret = fp.readline()

         if len(toret) == 0:
            raise StopIteration

         yield toret.strip()

   def rhel_release(self):

      txt = self.open_and_read("/etc/redhat-release")

      return

      for line in RELEASE:
            rhelreg3=re.compile()
            rhelmatch3=rhelreg3.match(line)
            rhelreg2AS=re.compile("Red Hat Linux Advanced Server release 2.1.*")
            rhelmatch2AS=rhelreg2AS.match(line)
            rhelreg2ES=re.compile(r"Red Hat Enterprise Linux ES release 2.1.*")
            rhelmatch2ES=rhelreg2ES.match(line)
            rhelregDesktop=re.compile(r"Red Hat Desktop release (\d)")
            rhelmatchDesktop=rhelregDesktop.match(line)
            
            if rhelmatch2AS or rhelmatch2ES:
                RELEASE.close()
                return '2.1'
            if rhelmatch3:
                RELEASE.close()
                return str(rhelmatch3.group(1))
            if rhelmatchDesktop:
                RELEASE.close()
                return str(rhelmatchDesktop.group(1))

   def get_hostname(self):

      fp = self.open("hostname")

      return fp.readline().strip()

   def kernel_version(self):

      return self.open_and_read("uname").split()[2]

   def get_mounts(self):

      for line in self.open("sos_commands/filesys/mount_-l").readlines():
         if len(line) > 0:
            yield line.split()

class sar_class:

   ksar_path = "/home/shnavid/downloads/kSar-4.0.12.jar"

   def __init__(self, parent_sos = None):

      self.files = []

      self.parent_sos = parent_sos

   def add_file(self, file):

      self.files.append(file)

   def search_date(self, find_date):

      for xfile in self.files:

         try:
            fp = open(xfile, "r")
            date = fp.readline().split()[-1]
            fp.close()
            if date == find_date:
               return xfile
            return xfile
         except:
            print "removing invalid file"
            self.files.remove(xfile)

   def graph(self, date, from_time = None, to_time = None):

      # Linux 2.6.9-67.ELhugemem (ux061.lvm.de)         2008-01-07

      fname = self.search_date( time.strftime("%Y-%m-%d", date) )

      if not fname:
         return False

      print """java -jar %s -input "%s" -outputPNG /tmp""" % (self.ksar_path, fname)



if __name__ == "__main__":

   sar = sar_class()
   sar.add_file("/misc/ibook/lvm_144277/ux061-184518/var/log/sa/sar13")
   print sar.graph( time.localtime() )
   pdb.set_trace()

#   prova = sosreport_class("/tmp/sosreport-ux061-272619-ae4f2a.tar.bz2")
#   prova = sosreport_class("/mnt/ibook/dell_gfs/fs01-lx.chipidea.com.2007082544936/")
   prova = sosreport_class("/tmp/sosreport-localhost-20080101173149-b8d7.tar.bz2", None)

   print prova.get_mounts()
   pdb.set_trace()
